/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.stakeholder;

import javax.faces.event.ActionEvent;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StakeholderAccountState;
import util.localization.WebLocalization;
import util.mailhelper.SMTPAuthenticator;
import util.generator.PasswordGenerator;

/**
 *
 * @author AdminNUS
 */
@ManagedBean
@RequestScoped
public class StakeholderForgotPasswordManagedBean implements Serializable {

    @EJB
    private StakeholderSessionBeanStateless stakeholderMgr;
    @EJB
    private SystemMessagesBean systemMessages;
    private WebLocalization localization;
    private StakeholderAccountState stakeholderAccountState;
    //  user preferred locale
    private String preferredLocale;
    private String username;
    private String bizRegNumber;
    private String email;
    private String emailServerName;
    private String emailFromAddress;
    private String toEmailAddress;
    private String mailer;
    private String name;
    private String password;
    private String subject;

    /** Creates a new instance of ForgotPasswordManagedBean */
    public StakeholderForgotPasswordManagedBean() {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
    }

    public void requestPassword(ActionEvent event) throws IOException {
        try {
            stakeholderAccountState = stakeholderMgr.getStakeholderByUsername(username);
        } catch (Exception e) {
        }
        try {
            if (!stakeholderAccountState.getBizRegNumber().equals(bizRegNumber)) {
                System.out.println(bizRegNumber);
                String invalidBizRegNum = systemMessages.getSystemMessage("INVALID_BIZREGNUMBER", preferredLocale);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, invalidBizRegNum, ""));
            } else {
                if (stakeholderAccountState != null) {
                    //staffAccountMgr.setSelectedLocale(preferredLocale);

                    if ((stakeholderAccountState.getUsername().equals(username)) && (stakeholderAccountState.getBizRegNumber().equals(bizRegNumber))) {
                        email = stakeholderAccountState.getCorpEmail();
                        PasswordGenerator pg = new PasswordGenerator();
                        password = pg.generatePassword(6);
                        System.out.println(password);

                        emailServerName = "smtp.gmail.com";
                        emailFromAddress = "Stakeholder ADMIN<auhiew@gmail.com>";
                        toEmailAddress = email;
                        mailer = "JavaMailer";

                        try {
                            Properties props = new Properties();
                            //props.put("mail.smtp.host", "smtp.gmail.com");
                            props.put("mail.smtp.host", emailServerName);
                            props.put("mail.smtp.socketFactory.port", "465");
                            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                            props.put("mail.smtp.auth", "true");
                            props.put("mail.smtp.port", "465");
                            props.put("mail.smtp.starttls.enable", "true");
                            props.put("mail.smtp.debug", "true");
                            javax.mail.Authenticator auth = new SMTPAuthenticator();

                            Session session = Session.getInstance(props, auth);
                            session.setDebug(true);
                            //Message msg = new MimeMessage(session);
                            MimeMessage msg = new MimeMessage(session);
                            if (msg != null) {
                                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                                subject = systemMessages.getSystemMessage("STAKEHOLDER_EMAIL_SUBJECT", preferredLocale);
                                msg.setSubject(subject, "UTF-8");

                                String passwordMsg1 = systemMessages.getSystemMessage("STAKEHOLDER_PASSWORD_MSG_1", preferredLocale);
                                String passwordMsg2 = systemMessages.getSystemMessage("STAKEHOLDER_PASSWORD_MSG_2", preferredLocale);
                                String passwordMsg3 = systemMessages.getSystemMessage("STAKEHOLDER_PASSWORD_MSG_3", preferredLocale);
                                String messageText = passwordMsg1 + " " + username + ",\n\n" + passwordMsg2 + "\n" + password + "\n\n" + passwordMsg3;
                                msg.setText(messageText, "UTF-8");
                                msg.setHeader("Content-Type", "text/plain; charset=UTF-8");
                                Date timeStamp = new Date();
                                msg.setSentDate(timeStamp);
                                Transport.send(msg);

                                String passwordSent = systemMessages.getSystemMessage("NEW_PASSWORD_SENT", preferredLocale);
                                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, passwordSent, ""));

                                stakeholderAccountState.setPassword(encrypt(password));

                                reset();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new EJBException(e.getMessage());
                        }
                    }
                } else {
                    String statusMessage = systemMessages.getSystemMessage("STAKEHOLDERACCOUNT_ACCT_DOES_NOT_EXIST", preferredLocale);
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void reset() {
        username = "";
        bizRegNumber = "";
    }

    public boolean validateEmailFormat(String emailInput) {
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(emailInput);
        boolean matchFound = m.matches();

        if (!matchFound) {
            // means error
            return false;
        }
        return true;
    }

    //encrypting the password
    public String encrypt(String inputString) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String outputString = util.service.PasswordService.getInstance().encrypt(inputString);
        return outputString;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getBizRegNumber() {
        return bizRegNumber;
    }

    public void setBizRegNumber(String bizRegNumber) {
        this.bizRegNumber = bizRegNumber;
    }
}
